import os
from urllib import request, parse
import argparse
import base64
import json

try:
    from .cvio import cvio
except:
    from cvio import cvio

def loadBatchEncodedImages(src, batch_size):
    img_list = cvio.load_image_list(src, recursive=True,silent=False)
    n = len(img_list)
    tbar = range(0, n, batch_size)
    m = len(tbar)
    c =0
    for i, start in enumerate(tbar,1):
        end = min(start + batch_size, n)
        imgs, labels = [], []
        for j in range(start, end, 1):
            imgpath = img_list[j]
            label = imgpath.split(os.sep)[-2]
            try:
                imgs.append(encodeImg(imgpath))
                labels.append(label)
                c += 1
            except:
                print('Exception, continue', imgpath)
        print('Uploading batch [%d/%d] [%d] %.2f%%' % (i, m, c, i / m*100))
        yield imgs, labels
        

def encodeImg(imgName):
    encodestr = ''
    with open(imgName, 'rb') as f:
        data = f.read()
        encodestr = base64.b64encode(data)
    return encodestr


def deleteHDF5BaseOnline(url, featureRoute, password=''):
    if not password or password != 'abc123..':
        print('密码验证错误, 无法删除.')
        return
    res = deleteHDF5Base(url, featureRoute)
    if not res['status']:
        print('删除失败 %s.' % featureRoute)
    else:
        print('删除成功 %s.' % featureRoute)

def deleteHDF5Base(url, featureRoute):
    data = {'uroute': featureRoute}
    data = bytes(parse.urlencode(data), encoding='utf-8')
    req = request.Request('%s/deleteHDF5Base' % url, data=data)
    res = request.urlopen(req).read()
    res = bytes.decode(res)
    res = json.loads(res)
    return res

def insertIndex(src, featureRoute, url='http://172.16.1.186:9091/detService', batch_size=256):
    dataloader = loadBatchEncodedImages(src, batch_size=batch_size)
    n = 0
    for i, (images, labels) in enumerate(dataloader,1):
        n += len(images)
        print('%d [%d]' % (i, n))
        data = dict(images=images, labels=labels, uroute=featureRoute)
        data = bytes(parse.urlencode(data), encoding='utf-8')
        req = request.Request('%s/insertIndex' % url, data=data)
        res = request.urlopen(req).read()
        res = bytes.decode(res)
        res = json.loads(res)
        if not res['status']:
            print('插入新数据失败.', i)
            return res
    print('已载入指纹至Faiss显存.')
        
def updateIndex(url, data):
    data = bytes(parse.urlencode(data), encoding='utf-8')
    req = request.Request('%s/updateIndex' % url, data=data)
    res = request.urlopen(req).read()
    res = bytes.decode(res)
    res = json.loads(res)
    return res


def index2HDF5Base(url, featureRoute):
    url = '%s/index2HDF5Base' % url
    data = {'uroute': featureRoute}
    data = bytes(parse.urlencode(data), encoding='utf-8')
    req = request.Request(url, data=data)
    res = request.urlopen(req).read()
    res = bytes.decode(res)
    res = json.loads(res)

    if res['status']:
        print('已同步保存指纹数据至本地.')
    else:
        print("同步保存指纹数据至本地失败.")

    return res

def syncInsertIndex(url, featureRoute='', imageFolder='', batchSize=256, sync=False, reset=False):
    if featureRoute:
        res = updateIndex(url, data={'reset': reset})
        if res['status']:
            print('已重置未学习索引库.')
        else:
            print('重置未学习索引库失败.')

    if imageFolder:
        if os.path.exists(imageFolder):
            insertIndex(imageFolder, featureRoute, url, batchSize)
        else:
            print("路径不存在（%s）." % imageFolder)

    if sync:
        index2HDF5Base(url, featureRoute)

    if featureRoute:
        res = updateIndex(url, data={'uroute': featureRoute})
        if res['status']:
            print('已切换未学习索引库路由至%s.' % featureRoute)
        else:
            print('切换未学习索引库路由失败.')

if __name__ == '__main__':
    pass
